<?php
class mysql {
	var $link;
	var $lastInsertId;
	var $queryInfo;
	var $dbInfo;
	
	function mysql($dbInfo) {
		$this->__construct($dbInfo);
	}
	
	function __construct($dbInfo) {
		$this->link = false;
		$this->lastInsertId = false;
		$this->queryInfo = array(
			'queries' => array(),
			'last_query' => '',
			'total' => 0
		);
		$this->dbInfo = array();
		
		$this->dbInfo['host'] = (!empty($dbInfo['host'])) ? $dbInfo['host'] : 'localhost';
		$this->dbInfo['username'] = (!empty($dbInfo['username'])) ? $dbInfo['username'] : '';
		$this->dbInfo['password'] = (!empty($dbInfo['password'])) ? $dbInfo['password'] : '';
		$this->dbInfo['database'] = (!empty($dbInfo['database'])) ? $dbInfo['database'] : '';
		
		$this->connect();
	}
	
	function __destruct() {
		$this->close();
	}
	
	function close() {
		if ($this->link) @mysql_close($this->link);
		
		return true;
	}
	
	function connect() {
		$this->link = mysql_connect($this->dbInfo['host'], $this->dbInfo['username'], $this->dbInfo['password']) or die('MySQL error: '.mysql_error());
		@mysql_select_db($this->dbInfo['database'], $this->link) or die('MySQL error: '.mysql_error());
		
		return true;
	}
	
	function delete($table, $where, $limit = 1) {
		if (empty($where)) return false;
		
		$limitStr = '';
		$limit = (int)$limit;
		if ($limit > 0) $limit .= ' LIMIT '.$limit;
		return $this->query('DELETE FROM `'.$table.'` WHERE '.$where.$limitStr);
	}
	
	// Data for insert function shouldn't be escaped
	function insert($table, $data) {
		if (empty($table) || empty($data)) return false;
		
		$query = 'INSERT INTO `'.$table.'` (`'.implode('`, `', array_keys($data)).'`) VALUES("'.implode('", "', array_map('escape', $data)).'")';
		$result = $this->query($query);
		if ($result === true)
			$this->lastInsertId = mysql_insert_id($this->link);
		
		return $result;
	}
	
	function query($query) {
		if (empty($query)) return false;
		if (!is_resource($this->link)) $this->connect();
		
		$this->queryInfo['last_query'] = $query;
		$result = mysql_query($query, $this->link) or die('MySQL error: '.mysql_error());
		
		if ($result !== false) {
			$this->queryInfo['queries'][] = $query;
			++$this->queryInfo['total'];
			
			return $result;
		} else
			return false;
	}
	
	// Data for update function shouldn't be escaped
	function update($table, $data, $where, $limit = 1) {
		if (empty($table) || empty($data) || !is_array($data) || empty($where)) return false;
		
		$query_format = array();
		foreach($data as $key => $value)
			$query_format[] = "`$key` = '".escape($value)."'";
		
		$limitStr = '';
		$limit = (int)$limit;
		if ($limit > 0) $limit .= ' LIMIT '.$limit;
		$query = 'UPDATE `'.$table.'` SET '.implode(', ', $query_format).' WHERE '.$where.$limitStr;
		return $this->query($query);
	}
}

if (!function_exists('escape')) {
	function escape($str = '') {
		return addslashes($str);
	}
}
?>